package com.qq.spirit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qq.spirit.db.DBUtil;
import com.qq.spirit.model.UserData;

public class AccountSyncTask implements Runnable
{

	@Override
	public void run()
	{
		try
		{
			List<Map<String, String>> userList = DBUtil.executeQuery("select * from u_user");
			Map<String, String> validateUser = new HashMap<String, String>();
			for (Map<String, String> user : userList)
			{
				validateUser.put(user.get("username"), user.get("state"));
			}
			List<Map<String, String>> gameUserList = DBUtil.executeQuery("select * from u_game_user ");
			for (Map<String, String> gameUser : gameUserList)
			{
				int gid = Integer.parseInt(gameUser.get("gid"));
				// 如果帐号是非法的，则从缓存中移除
				String user = gameUser.get("username");
				if (validateUser.containsKey(user))
				{
					String userstate = validateUser.get(user);
					if (userstate.equals("0"))
					{
						// 合法，看看游戏号是否已经合法
						String gamestate = gameUser.get("state");
						if (gamestate.equals("0"))
						{
							UserData uData = GameUserInfoUtil.getUser(gid);
							if (uData == null)
							{
								uData = new UserData(gid);
								uData.setAllGameInfo(gameUser);
								GameUserInfoUtil.putUser(gid, uData);
								loadConfig(uData, gid);
								LoggerUtil.sys("加载用户："+gid);
							} else
							{
								// 合法
								String curr_ver = gameUser.get("curr_ver");
								String last_ver = gameUser.get("last_ver");
								if (!curr_ver.equals(last_ver))
								{
									loadConfig(uData,gid);
									LoggerUtil.sys("更新用户配置項："+gid);
								}
							}
						} else
						{
							GameUserInfoUtil.removeUser(Integer.parseInt(gameUser.get("gid")));
						}
					} else
					{
						GameUserInfoUtil.removeUser(Integer.parseInt(gameUser.get("gid")));
					}
				} else
				{
					GameUserInfoUtil.removeUser(Integer.parseInt(gameUser.get("gid")));
				}
				GameUserInfoUtil.setIsUserLoadSuc(true);
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void loadConfig(UserData uData, int gid)
	{
		// 需要加载配置项
		List<Map<String, String>> configList = DBUtil.executeQuery("select * from u_game_config where gid=" + gid);
		for (Map<String, String> config : configList)
		{
			uData.putConfig(config.get("config_name"), config.get("config_value"));
		}
		DBUtil.executeUpdate("update u_game_user set last_ver = curr_ver where gid="+gid);
	}
}
